package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信验证码
     * @param user
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest httpServletRequest) {
        //获取手机号
        String phone = user.getPhone();
        //随机生成4位数的验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //发送短信
        log.info("验证码为：{}",code);
//        SMSUtils.sendMessage("菩提阁","xxx",phone,code);
        //将生成的验证码存入session，方便后续验证
//        httpServletRequest.getSession().setAttribute(phone,code);

        //将生成的验证码存入redis数据库
        redisTemplate.opsForValue().set("phone",code,5, TimeUnit.MINUTES);
        return R.success("短信发送成功，请注意查收验证码");
    }

    /**
     * 移动端用户登录
     * @param map
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/login")
    public R<User> userLogin(@RequestBody Map map,HttpServletRequest httpServletRequest) {
        //获取登录信息
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");

        //从session中获取在给用户发送短信前生成的验证码
        //String sessionCode = (String) httpServletRequest.getSession().getAttribute(phone);

        //从redis中获取验证码
        String redisCode = (String) redisTemplate.opsForValue().get("phone");

        //校验
        if (code != null && code.equals(redisCode)) {

            //判断是否为新用户，若为新用户，需要对其进行注册
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(userLambdaQueryWrapper);

            //新用户，对其进行注册
            if (user == null) {
                user = new User();
                user.setPhone(phone);

                //插入数据库
                userService.save(user);
            }

            httpServletRequest.getSession().setAttribute("user",user.getId());

            //登录成功，删除redis中的验证码
            redisTemplate.delete("phone");
            return R.success(user);
        }

        return R.error("登录失败");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest httpServletRequest) {
//        1、清理Session中的用户id
        httpServletRequest.getSession().removeAttribute("user");
//        2、返回结果
        return R.success("退出成功");
    }
}
